package com.dc.wifi.main.ui.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.dc.wifi.R;
import com.google.gson.JsonObject;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

public class PayActivity extends AppCompatActivity {
    private final int SDK_PAY_FLAG = 100;
    private final Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == SDK_PAY_FLAG) {
                // 处理消息
                LogUtils.d("PAYTAG", "Received message with ID: " + msg.obj);
                ToastUtils.showShort(msg.obj.toString());
                // 这里可以执行更多的逻辑
            }
            return true;
        }
    });

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        findViewById(R.id.btn_alipay).setOnClickListener(v -> {
            OkGo.<String>post("http://8.130.82.40:18080/api/v1/auth/topUpVIP")
                    .upJson("{\"id\":1,\"money\":30,\"days\":30,\"vipType\":\"00\",\"title\":\"1个月会员\",\"subtitle\":\"\",\"description\":\"新人优惠\",\"discount\":28.98}")
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            LogUtils.d(response.body());
                            try {
                                JSONObject jsonObject = new JSONObject(response.body());
                                String data = jsonObject.optString("data");
                                pay(data);
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }


                        }
                    });
        });
        findViewById(R.id.btn_alipay2).setOnClickListener(v -> {
            OkGo.<String>post("http://8.130.82.40:18080/api/v1/auth/topUpVIP")
                    .upJson("{\"id\":2,\"money\":60,\"days\":60,\"vipType\":\"00\",\"title\":\"2个月会员\",\"subtitle\":\"\"}")
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            LogUtils.d(response.body());
                            try {
                                JSONObject jsonObject = new JSONObject(response.body());
                                String data = jsonObject.optString("data");
                                pay(data);
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }


                        }
                    });
        });

    }

    /**
     * 支付（加签过程不允许在客户端进行，必须在服务端，否则有极大的安全隐患）
     *
     * @param orderInfo 加签后的支付请求参数字符串（主要包含商户的订单信息，key=value形式，以&连接）。
     */
    private void pay(final String orderInfo) {
        final Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                //第二个参数设置为true，将会在调用pay接口的时候直接唤起一个loading
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
}
